package top.yuyufeng.mbuy.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import top.yuyufeng.mbuy.constant.SessionConstant;
import top.yuyufeng.mbuy.dto.ResponseJson;
import top.yuyufeng.mbuy.dto.UserDTO;
import top.yuyufeng.mbuy.entity.User;
import top.yuyufeng.mbuy.exception.UserException;
import top.yuyufeng.mbuy.service.IUserService;
import top.yuyufeng.mbuy.utils.SessionUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author yuyufeng7
 */
@Controller
public class LoginController {


    @Autowired
    private IUserService userService;


    @Autowired
    private SessionUtil sessionUtil;


    @RequestMapping(value = "toLogin", method = RequestMethod.GET)
    public String toLogin() {
        return "login";
    }

    @RequestMapping(value = "doLogin", method = RequestMethod.POST)
    public @ResponseBody
    ResponseJson
    doLogin(HttpServletResponse httpServletResponse, @RequestBody UserDTO userDTO) {
        try {
            UserDTO result = userService.checkPassword(userDTO);
            sessionUtil.setSession(httpServletResponse, result, SessionConstant.SESSION_USER);
        } catch (UserException e) {
            return ResponseJson.fail(e.getErrorMsg());
        }
        return ResponseJson.success();
    }

    @RequestMapping(value = "doLogout", method = RequestMethod.GET)
    public @ResponseBody
    ResponseJson doLogout(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
        sessionUtil.deleteSession(httpServletRequest, httpServletResponse, SessionConstant.SESSION_USER);
        return ResponseJson.success("退出登录");
    }


}
